const cp = require('child_process')
const { resolve } = require('path')
const mongoose = require('mongoose')
const Movie = mongoose.model('Movie')
const Category = mongoose.model('Category')

;
(async() => {

    // 数据库查询电影数据
    let movies = await Movie.find({
        $or: [
            { video: { $exists: false } },
            { video: null },

        ]
    })


    // 脚本地址
    const script = resolve(__dirname, '../crawler/video')

    //生成子进程 
    child = cp.fork(script, [])
    let invoked = false

    child.on('error', err => {
        if (invoked) return
        invoked = true
        console.log(err)
    })

    //进程退出时
    child.on('exit', code => {
        if (invoked) return
        invoked = false

        let err = code === 0 ? null : new Error('exit code ' + code)

        console.log(err)
    })

    child.on('message', async data => {

        let doubanId = data.doubanId
        let movie = await Movie.findOne({
            doubanId: doubanId
        })

        // 判断是否有预告片，没有就移除
        if (data.video) {
            movie.video = data.video
            movie.cover = data.cover

            await movie.save()
        } else {
            await movie.remove()

            let movieTypes = movie.movieTypes

            // 删除分类
            for (let i = 0; i < movieTypes.length; i++) {
                let type = movieTypes[i]
                let cat = Category.findOne({
                    name: type
                })

                if (cat && cat.movies) {
                    let idx = cat.movies.indexOf(movie._id)
                    if (idx > -1) {
                        cat.movies = cat.movies.splice(idx, 1)
                    }

                    await cat.save()
                }
            }


        }
        console.log('-----------------')
        console.log(data)
    })

    child.send(movies)


})()